"""
Author: Jian SuiYue kaohx0214@yeah.net
Date: 2025-05-15 10:35:00
LastEditTime: 2025-05-15 17:09:15
FilePath: LibraryManagerStudio/web/routes/session_api.py
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi.responses import JSONResponse

from .token_api import validate_jwt
from ..deps import get_db
from ...database import DBManager
from ...datamodel import Session, User

router = APIRouter()

"""
/get/{session_id}
/gets
/new
/update
/delete/{session_id}
"""


@router.get("/get")
async def get_session(
        login: str = Query(...),
        uid: int = Query(..., ge=1),
        db: DBManager = Depends(get_db)
):
    """
    Get the new session detail 

    GET /get?login={your_token}&uid={uid}
    Args:
        login: Token.id
        uid: User.id
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # check user exist
    user_exist = db.get(User, filters={"id": uid})
    if not user_exist.data or not user_exist.status:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User ID {uid} not found")
    # get session
    session = db.get(Session, filters={"user_id": uid}, order="desc")  # create at desc
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": session.data[0], "message": "Get session detail successful"}
    )


@router.post("/gets")
async def get_sessions(
        login: str = Query(...),
        uid: str = Query(..., ge=1),
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        db: DBManager = Depends(get_db)
):
    """
    Get session list.

    POST /gets?login={your_token}&page={page}&size={size}
    Args:
        token: Token.id
        pageinfo: PageInfo
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # get session list
    result = db.get(Session, filters={"user_id": uid}, page_info={"page": page, "size": size})
    if not result.status or not result.data:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unexpected Error: {result.message}")
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": result.data, "message": "Get sessions successful"}
    )


@router.post("/new")
async def new_session(
        login: str = Query(...),
        uid: str = Query(..., ge=1),
        db: DBManager = Depends(get_db)
):
    """
    Create a new session.

    POST /new?login={your_token}&uid={uid}
    Args:
        token: Token.id
        uid: User.id
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # check user exist
    user_exist = db.get(User, filters={"id": uid})
    if not user_exist.data or not user_exist.status:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"User ID {uid} not found")
    # update
    session = Session(user_id=uid)
    result = db.upsert(session)
    if not result.status or not result.data:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unexpected error at creating session")
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "data": result.data[0], "message": "Create session successful"}
    )


@router.delete("/delete")
async def delete_session(
        login: str = Query(...),
        session_id: int = Query(..., ge=1),
        db: DBManager = Depends(get_db)
):
    """
    Delete the session.

    DELETE /delete?login={your_token}&session_id={session_id}
    Args:
        login: Token.id
        session_id: Session.id
        db: DBManager
    """
    # verify
    validate_jwt(login)
    # check session exist
    session = db.get(Session, filters={"id": session_id})
    if not session.status or not session.data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Session ID {session_id} not found")
    # delete
    result = db.delete(Session, filters={"id": session_id})
    if not result.status or not result.data:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unexpected Error: {result.message}")
    # return
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={"status": True, "message": "Delete session successful"}
    )
